/**
 * 
 */
package cyclopean.world;

import java.util.HashMap;
import java.util.Map;

import javax.media.opengl.GL;

import cyclopean.VideoProperties;
import cyclopean.world.zone.Position;
import cyclopean.world.zone.Zone;
import cyclopean.world.zone.ZoneRenderer;

import javagame.core.io.Screen.ScreenRenderer;

// TODO Javadoc
/**
 * 
 *
 * @author Jaco van der Westhuizen
 */
class WorldRenderer implements ScreenRenderer
{
	final Player player;
	final Map<Zone, ZoneRenderer> renderers = new HashMap<Zone, ZoneRenderer>();
	
	private float aspectRatio = 1.0f;

	WorldRenderer(Player player)
	{
		this.player = player;
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.Screen.ScreenRenderer#renderForDisplay(javax.media.opengl.GL)
	 */
	@Override
	public void renderForDisplay(GL gl)
	{
		if (player.getPawn() == null)
			return;

	
		// Perspective matrix
		gl.glMatrixMode(GL.GL_PROJECTION);
		gl.glFrustum(-0.5, 0.5, -0.5 * aspectRatio, 0.5 * aspectRatio, 0.5, 1000.0); // FoV = 90 degrees

		// ModelView Matrix
		gl.glMatrixMode(GL.GL_MODELVIEW);
		
		// TODO Use relative head position

		final Position pos = player.getPawn().pos;
		pos.apply(gl);

		Zone zone = pos.getZone();

		// TODO See through portals
		{
    		ZoneRenderer renderer = renderers.get(zone);
    
    		if (renderer == null)
    		{
    			renderer = new ZoneRenderer(gl, zone);
    			renderers.put(zone, renderer);
    		}

    		renderer.render(gl);
		}
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.Screen.ScreenRenderer#renderForPicking(javax.media.opengl.GL)
	 */
	@Override
	public void renderForPicking(GL gl)
	{
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.Screen.ScreenRenderer#loadAssets(javax.media.opengl.GL, boolean)
	 */
	@Override
	public void loadAssets(GL gl, boolean isInitial)
	{
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see javagame.core.io.Screen.ScreenRenderer#unloadAssets(javax.media.opengl.GL, boolean)
	 */
	@Override
	public void unloadAssets(GL gl, boolean isFinal)
	{
		for (ZoneRenderer render : renderers.values())
		{
		    render.unload(gl);
		}

		if (isFinal)
		{
		    ZoneRenderer.unloadStatic(gl);
		}
	}

	/* (non-Javadoc)
	 * @see javagame.core.io.Screen.ScreenRenderer#onScreenReshape(int, int)
	 */
	@Override
	public void onScreenReshape(int width, int height)
	{
		aspectRatio = VideoProperties.calculateAspectRatio(width, height);
	}
}
